import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/net/method/base_method.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/manage/adjust/adjustmodel.dart';
import 'package:opene/ui/manage/managedialogscreen.dart';
import 'package:toast/toast.dart';

class CCLocationSubmitScreen extends StatelessWidget {
  CycleCountBean cycleCountBean;

  CCLocationSubmitScreen({this.cycleCountBean});

  @override
  Widget build(BuildContext context) {
    return CCLocationSubmitScreenPage(cycleCountBean: cycleCountBean);
  }
}

class CCLocationSubmitScreenPage extends StatefulWidget {
  CycleCountBean cycleCountBean;

  CCLocationSubmitScreenPage({this.cycleCountBean});

  @override
  _CCLocationSubmitPageState createState() => _CCLocationSubmitPageState(cycleCountBean: cycleCountBean);
}

class _CCLocationSubmitPageState extends BaseState<CCLocationSubmitScreen> {
  CycleCountBean cycleCountBean;
  List<ReturnCycleListDTO> data = new List();

  _CCLocationSubmitPageState({this.cycleCountBean});

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "CycleCount: Scan Sku";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      next = "Submit";
    });
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  Text(
                    "Location: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                  Text(
                    "IBLPN: ",
                    style: TextStyle(color: MyAppTheme.color_666666, fontSize: 14.0),
                  ),
                ],
              ),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      Utils.getStringisEmpty(cycleCountBean.location),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                    Text(
                      Utils.getStringisEmpty(cycleCountBean.lpn),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(color: MyAppTheme.color_333333, fontSize: 14.0),
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(
            height: 5,
          ),
          ConstrainedBox(
            constraints: BoxConstraints(maxHeight: 35),
            child: TextField(
              controller: textEditingController,
              textInputAction: TextInputAction.search,
              keyboardType: TextInputType.number,
              onSubmitted: (String text) {
                print('Searching for $text');
                if (Utils.isEmpty(text)) {
                  return;
                }
                productGet(text);
              },
              // autofocus: true,
              decoration: InputDecoration(
                suffixIcon: IconButton(
                  padding: EdgeInsets.all(2.0),
                  icon: Icon(
                    Icons.qr_code_scanner,
                    size: 28,
                    color: MyAppTheme.nearlyBlue,
                  ),
                  onPressed: () {
                    // requestPermissions();
                    // Utils.scanBarcode(context);
                    Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                      return ScanCode();
                    })).then((text) {
                      if (text == null) {
                        return;
                      }
                      setState(() {
                        textEditingController.text = text;
                      });
                      print(text); //拿到扫描结果
                      productGet(text);
                    });
                  },
                ),
                border: OutlineInputBorder(
                  borderSide: BorderSide(
                    color: MyAppTheme.nearlyBlue,
                  ),
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                enabledBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点之外的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                focusedBorder: OutlineInputBorder(
                  borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                  // 设置焦点时的边框颜色
                  borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                ),
                hintText: "Please enter the quantity",
                filled: true,
                fillColor: MyAppTheme.white,
                //隐藏下划线
                //border: InputBorder.none,
                hintStyle: TextStyle(color: Colors.grey),
                contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
              ),
              onChanged: (text) {
                code = text;
              },
            ),
          ),
        ],
      ),
    );
  }

  void productGet(String barcode) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["barcode"] = barcode;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.product, method: BaseMethod.post, data: json);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      String sku = baseResponse.data;

    }else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void returnCycleCountSkuSubmit(CycleCountQr cycleCountQr) async {
    updateHint('');

    String json = jsonEncode(cycleCountQr);
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.cycleCountSkuSubmit, method: BaseMethod.post, data: json);
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      CycleCountSku cycleCountSku2 = CycleCountSku.fromJson(baseResponse.data);
      if (cycleCountQr.taskId != null) {
        cycleCountSku2.taskId = cycleCountQr.taskId;
      }
      cycleCountSku2.barcode = cycleCountSku.barcode;
      Navigator.of(context).pop(cycleCountSku2);
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    ToastContext().init(context);
    if (Utils.isEmpty(textEditingController.text)) {
      Toast.show("Please enter the quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    if (!Utils.isInteger(textEditingController.text)) {
      Toast.show("Please enter the quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    int afterQty = int.parse(textEditingController.text);
    if (afterQty < 0) {
      Toast.show("Please enter the quantity", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }

    CycleCountQr cycleCountQr = new CycleCountQr(cycleCountSku.barcode, cycleCountSku.inventory.lpn, afterQty, cycleCountSku.taskId);

    if (Utils.getIntegerisEmpty(afterQty) - Utils.getIntegerisEmpty(cycleCountSku.inventory.quantity) != null) {
      showDialog(
        context: context,
        builder: (context) => CCSkuTrkDialog(inventory: cycleCountSku.inventory.quantity, qty: afterQty),
      ).then((value) => {
            print("result2:${value}"),
            if ((value != null) && (value == "ok")) {returnCycleCountSkuSubmit(cycleCountQr)}
          });
      return;
    }
    returnCycleCountSkuSubmit(cycleCountQr);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}

class CycleCountQr {
  String sku;
  String lpn;
  int afterQty;
  int taskId;

  CycleCountQr(String sku, String lpn, int afterQty, int taskId) {
    this.sku = sku;
    this.lpn = lpn;
    this.afterQty = afterQty;
    this.taskId = taskId;
  }

  Map<String, dynamic> toJson() {
    return {
      "sku": this.sku,
      "lpn": this.lpn,
      "afterQty": this.afterQty,
      "taskId": this.taskId,
    };
  }
}
